package upload

import (
	"context"
	"fmt"
	"go.manyji.com/lib/encoding/json"
	"mime/multipart"
	"net/http"
	"sieve_admin_server/app/contextx"
	"sieve_admin_server/app/server"
)

type Uploader interface {
	API_upload_file(ctx *server.Context) interface{}
}

func Handle(ctx *server.Context, w http.ResponseWriter, r *http.Request, fCallBack func(ctx context.Context, f multipart.File, header *multipart.FileHeader) (string, error)) interface{} {

	w.Header().Set("Access-Control-Allow-Origin", "*")

	//从请求当中判断方法
	ret := map[string]interface{}{
		"code":     0,
		"msg":      "success",
		"filename": "",
	}

	file, head, err := r.FormFile("file")
	if err != nil {
		ret["msg"] = fmt.Sprintf("%+v", err)
		ret["code"] = -1
		return ret
	}

	extraArgs := contextx.GetRequestArgs(ctx,
		[]contextx.Var{
			contextx.NewVar("platform"),
		},
	)

	c := context.WithValue(context.Background(),
		"platform", extraArgs["platform"])

	defer file.Close()

	fileName, err := fCallBack(c, file, head)
	if err != nil {
		ret["msg"] = fmt.Sprintf("%+v", err)
		return ret
	}

	ret["filename"] = fileName

	bt, _ := json.Marshal(ret)
	_, _ = w.Write(bt)
	return ret
}
